package com.wkh.generator;

import com.wkh.model.MainTemplateConfig;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.net.URL;

/**
 * @author wkh
 * 动态生成模板类
 */
public class DynamicallyGenerated {
    public static void main(String[] args) throws IOException, TemplateException {
        String property = System.getProperty("user.dir");
        String inputPath = property + File.separatorChar + "src/main/resources/templates/MainTemplate.java.ftl";
        String outputPath = property + File.separatorChar + "MainTemplate.java";
        MainTemplateConfig model = new MainTemplateConfig("wkh", "和为", true);
        doGenerator(inputPath,outputPath,model);

    }

    public static void doGenerator(String inputPath,String outputPath,Object model) throws IOException, TemplateException {
        //创建configuration对象，指定freemarker版本
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);

/*//        String propertyPath = System.getProperty("user.dir");
        URL url = DynamicallyGenerated.class.getResource("/templates");
        if (url == null){
            System.out.println("文件路径为null");
            return;
        }
        String templatesPath = url.getPath();*/

        //指定模板文件路径
        File templateDir = new File(inputPath).getParentFile();
//        System.out.println(templateDir.getPath());
        configuration.setDirectoryForTemplateLoading(templateDir);
        //指定字符集
        configuration.setDefaultEncoding("UTF-8");

        //创建模板对象
        String templateName = new File(inputPath).getName();
        Template template = configuration.getTemplate(templateName);

        //创建数据模型

        //指定生成的文件
        FileWriter out = new FileWriter(outputPath);

        //处理并生成文件
        template.process(model,out);
        out.close();
    }
}
